package simplecoder.wizards;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;

import freemarker.template.TemplateException;

import simplecoder.ProjectBean;
import simplecoder.domain.Clazz;
import simplecoder.domain.Module;
import simplecoder.domain.jsp.Page;
import simplecoder.util.FileUtil;
import simplecoder.util.FreeMarkerUtil;

public class CodeGenerationWizard extends Wizard implements INewWizard
{

	private CodeGenerationWizardPage page;
	private ISelection selection;
	private ProjectBean projectVo;

	public CodeGenerationWizard() {
		super();
		setNeedsProgressMonitor(true);
//		setDefaultPageImageDescriptor(Activator.getImageDescriptor("icons/wizard.jpg"));
		setWindowTitle("代码生成");
	}

	@Override
	public void addPages() {
		page = new CodeGenerationWizardPage(selection);
		addPage(page);
	}

	@Override
	public boolean performFinish(){
		System.out.println("拿值:"+page.getModuleTitleText().getText());
		Module.getInstance().setTitle(page.getModuleTitleText().getText());
		
		
		IRunnableWithProgress op = new IRunnableWithProgress(){
			public void run(IProgressMonitor monitor) throws InvocationTargetException{
				monitor.beginTask("代码生成", 100);
				//-------------------------------------java代码生成-------------------------------------
				monitor.worked(1);
				monitor.subTask("java代码生成");
				try {
					IPackageFragmentRoot packageFragmentRoot = projectVo.getJavaProject().findPackageFragmentRoot(new Path(Module.getInstance().getSourcePath()));
					//判断存在的不生成
					generateClass(packageFragmentRoot, Module.getInstance().getDao());
					generateClass(packageFragmentRoot, Module.getInstance().getService());
					generateClass(packageFragmentRoot, Module.getInstance().getAction());
				} catch (Exception e){
					e.printStackTrace();
				}
				//-------------------------------------jsp代码生成-------------------------------------
				monitor.worked(1);
				monitor.subTask("jsp代码生成");
				
				try {
					//创建文件夹
					String directoryPath = projectVo.getWebInf() + "/template/" + StringUtils.uncapitalize(Module.getInstance().getPojo().getName()) ;
					
					generateJsp(directoryPath, Module.getInstance().getMain());
					generateJsp(directoryPath, Module.getInstance().getGrid());
					generateJsp(directoryPath, Module.getInstance().getEdit());
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				monitor.done();
			}

			private void generateClass(
					IPackageFragmentRoot packageFragmentRoot, Clazz clazz)
					throws JavaModelException, IOException, TemplateException {
				
				IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment(clazz.getPackName());
				if (!packageFragment.exists())
				{
					packageFragment = packageFragmentRoot.createPackageFragment(clazz.getPackName(), true, null);
				}
				String javaCode = "";
//				System.out.println("--------");
				javaCode = FreeMarkerUtil.dataToString(clazz.getParams(), clazz.getSuffix()+".java.ftl");
				
				if(javaCode==null){
					javaCode = "file not fond";
				}
//				System.out.println(javaCode);
//				System.out.println(clazz.getName()+"   name");
				packageFragment.createCompilationUnit(clazz.getName() + ".java", javaCode, true, new NullProgressMonitor());
			}
			
			private void generateJsp(String directoryPath, Page page)
					throws IOException, TemplateException {
				//另一个方法
				FileUtil.createDirectory(directoryPath);
				//创建文件
				System.out.println("创："+directoryPath +"/"+page.getName());
				String filePath = directoryPath + "/" + page.getName();
				FileUtil.createFile(filePath);
				//生成
				String jspCode = "";
				jspCode = FreeMarkerUtil.dataToString(page.getParams(), page.getSuffix()+".jsp.ftl");
				FileUtil.writeStringToFile(filePath, jspCode);
			}
		};

		try {
			getContainer().run(true, false, op);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		/**
		 * 刷新工程
		 */
		projectVo.refresh();

		return true;
	}

	//@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		
		this.selection = selection;
		projectVo = new ProjectBean(selection);
	}

}